/*
 * Copyright (c) 2011-2024, Cpjit (cpjit@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cpjit.data;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * <p>插入时自动写入创建时间、创建人信息
 * <p>更新时自动写入更新时间、更新人信息
 * <pre>
 * // 1. 在MybatisPlusConfig中配置MybatisPlusInterceptor
 * &#064;Bean
 * public MybatisPlusInterceptor mybatisPlusInterceptor(InnerInterceptor[] innerInterceptors) {
 *     MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
 *     Arrays.stream(innerInterceptors)
 *             .forEach(mybatisPlusInterceptor::addInnerInterceptor);
 *     return mybatisPlusInterceptor;
 * }
 * // 2. 在MybatisPlusConfig中配置AuditingInnerInterceptor
 * &#064;Bean
 * public AuditingInnerInterceptor auditingInnerInterceptor(ConversionService conversionService) {
 *     return new AuditingInnerInterceptor(auditingMatchers(), conversionService);
 * }
 * // 3. 在MybatisPlusConfig中配置创建信息、更新信息的处理逻辑
 *    &#064;Bean
 * public Map<AuditingMatcher, Function<AuditingContext, Object>> auditingMatchers() {
 *    return Map.of(
 *            // 执行insert语句时候的处理
 *            AuditingMatcher.annotationMatch(CreatedDate.class, SqlCommandType.INSERT), AuditingContext::getCurrentTime,
 *            AuditingMatcher.annotationMatch(CreatedBy.class, SqlCommandType.INSERT), MyBatisConfig::getUserId,
 *            AuditingMatcher.annotationMatch(LastModifiedDate.class, SqlCommandType.INSERT), AuditingContext::getCurrentTime,
 *            AuditingMatcher.annotationMatch(LastModifiedBy.class, SqlCommandType.INSERT), MyBatisConfig::getUserId,
 *            // 执行update语句时候的处理
 *            AuditingMatcher.annotationMatch(LastModifiedDate.class, SqlCommandType.UPDATE), AuditingContext::getCurrentTime,
 *            AuditingMatcher.annotationMatch(LastModifiedBy.class, SqlCommandType.UPDATE), MyBatisConfig::getUserId
 *    );
 * }
 *    // 4、定义获取当前登录用户ID的方法
 *     static Long getUserId(AuditingContext ctx) {
 *
 *     }
 * </pre>
 *
 * @author yonghuan[cpjit@qq.com]
 */
public class AuditingInnerInterceptor implements InnerInterceptor {

    private final Map<AuditingMatcher, Function<AuditingContext, Object>> matchers;
    private final Supplier<ConversionService> conversionServiceSupplier;
    private ConversionService conversionService;

    public AuditingInnerInterceptor(Map<AuditingMatcher, Function<AuditingContext, Object>> matchers
            , ConversionService conversionService) {
        this.matchers = matchers;
        this.conversionServiceSupplier = () -> conversionService;
        this.conversionService = conversionService;
    }

    public AuditingInnerInterceptor(Map<AuditingMatcher, Function<AuditingContext, Object>> matchers
            , Supplier<ConversionService> conversionServiceSupplier) {
        this.matchers = matchers;
        this.conversionServiceSupplier = conversionServiceSupplier;
    }

    private void beforeUpdateInternal(MappedStatement ms, LambdaUpdateWrapper ew, LocalDateTime currentTime) {
        if (ms.getSqlCommandType() != SqlCommandType.UPDATE) {
            return;
        }
        Class entityClass = ew.getEntityClass();
        if (entityClass == null) {
            return;
        }
        final Map<String, Object> paramNameValuePairs = ew.getParamNameValuePairs();
        TableInfoHelper.getTableInfo(entityClass)
                .getFieldList()
                .forEach(column -> {
                    Field field = column.getField();
                    Arrays.stream(field.getAnnotations())
                            .forEach(annotation -> {
                                AuditingContext ctx = new AuditingContextImpl(ms.getSqlCommandType(), annotation, currentTime);
                                matchers.keySet()
                                        .stream()
                                        .filter(matcher -> matcher.matches(ctx))
                                        .findFirst()
                                        .ifPresent(matcher -> {
                                            Function<AuditingContext, Object> callback = matchers.get(matcher);
                                            final String paramName = field.getName() + "_";
                                            paramNameValuePairs.put(paramName, getValue(field, ctx, callback));
                                            // 参考的com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor#setVersionByWrapper方法
                                            ((Update<?, ?>) ew).setSql(String.format("%s = #{%s.%s}", column.getColumn(), "ew.paramNameValuePairs", paramName));
                                        });
                            });
                });
    }

    private Object getValue(Field field, AuditingContext ctx, Function<AuditingContext, Object> callback) {
        Object value = callback.apply(ctx);
        if (value != null && value.getClass() != field.getType()) {
            if (conversionService == null) {
                conversionService = conversionServiceSupplier.get();
            }
            value = conversionService.convert(value, field.getType());
        }
        return value;
    }

    private void beforeUpdateInternal(MappedStatement ms, Object entity, LocalDateTime currentTime) {
        Class<?> entityClass = entity.getClass();
        // 代理类
        while (entityClass.getName().contains("$$") && entityClass != Object.class) {
            entityClass = entityClass.getSuperclass();
        }
        if (entityClass.getAnnotation(TableName.class) == null) {
            return;
        }
        TableInfoHelper.getTableInfo(entityClass)
                .getFieldList()
                .forEach(column -> {
                    Field field = column.getField();
                    ReflectionUtils.makeAccessible(field);
                    Arrays.stream(field.getAnnotations())
                            .forEach(annotation -> {
                                AuditingContext ctx = new AuditingContextImpl(ms.getSqlCommandType(), annotation, currentTime);
                                matchers.keySet()
                                        .stream()
                                        .filter(matcher -> matcher.matches(ctx))
                                        .findFirst()
                                        .ifPresent(matcher -> {
                                            Function<AuditingContext, Object> callback = matchers.get(matcher);
                                            ReflectionUtils.setField(field, entity, getValue(field, ctx, callback));
                                        });
                            });
                });
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        Object entity = null;
        LambdaUpdateWrapper updateWrapper = null;
        if (parameter instanceof Map) {
            // 取到实体类
            Map<String, Object> map = (Map<String, Object>) parameter;
            if (map.containsKey(Constants.ENTITY)) {
                entity = ((Map<String, Object>) parameter).get(Constants.ENTITY);
            }
            final Object ew = map.getOrDefault(Constants.WRAPPER, null);
            if (ew instanceof LambdaUpdateWrapper<?> lambdaUpdateWrapper) {
                updateWrapper = lambdaUpdateWrapper;
            }
        } else {
            entity = parameter;
        }
        if (entity != null && TableInfoHelper.getTableInfo(entity.getClass()) == null) {
            entity = null;
        }
        LocalDateTime currentTime = LocalDateTime.now();
        if (entity != null) {
            beforeUpdateInternal(ms, entity, currentTime);
        }
        // 针对LambdaUpdateWrapper的处理
        if (updateWrapper != null) {
            beforeUpdateInternal(ms, updateWrapper, currentTime);
        }
    }
}
